<?php
/*
 * $HeadURL:https://loveapple.dev.java.net/svn/loveapple/trunk/src/php/main/application/lib/template/plugins/function.message.php $
 * $Author:loveapple $
 * $Revision:651 $
 * $Date:2009-04-15 12:31:36 +0900 (?, 15 4 2009) $
 *
 * ====================================================================
 *
 * Copyright (C) 2008 by loveapple.sourceforge.jp
 *
 * All copyright notices regarding loveapple and loveapple CoreLib
 * MUST remain intact in the scripts, documents and source code.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Correspondence and Marketing Questions can be sent to:
 * info at loveapple
 *
 * @author: loveapple
 */
require_once 'Zend/View/Exception.php';
require_once 'Smarty.class.php';
include_once 'i18n.php';

/**
 *
 * @author hao_shunri
 * @version $Revision$
 * @date $Date$
 * @id $Id$
 *
 */
class Third_Smarty extends Zend_View {

	/**
     * Default view partial
     *
     * @var string
     */
    protected static $_defaultViewPartial = null;
    
	private $_placeHolders = array();
	
	public $_zendView;
	
	public  $_helpers;

    protected $config;

	public $compiler_class = 'Third_SmartyAdvancedCompiler';
    
	protected $_smarty;

    /**
     *
     *
     * @param string $tmplPath
     * @param array $extraParams
     * @return void
     */
    public function __construct($tmplPath = null, $extraParams = array())
    {
    	$this->config  = Zend_Registry::get("config");
    	
        $this->initPath();
        
        if (null !== $tmplPath) {
            $this->setScriptPath($tmplPath);
        }

        foreach ($extraParams as $key => $value) {
            $this->key = $value;
        }
        
    }

    public function initPath(){

    	$this->_smarty = new Smarty();
    	
    	$this->_smarty->template_dir 	= $this->config->document_root.$this->config->view_path;
		$this->_smarty->compile_dir 		= $this->config->document_root.$this->config->view_path_c;
		$this->_smarty->cache_dir 		= $this->config->document_root.$this->config->view_path_cache;
		$this->_smarty->compile_check 	= true;
		$this->_smarty->debugging 		= false;
		$this->_smarty->caching 		= false;
		$this->_smarty->cache_lifetime 	= -1;
		$this->_smarty->force_compile	= true;
		
		$this->_smarty->register_outputfilter("smarty_prefilter_i18n");
		
		$this->_smarty->assign_by_ref('zf', $this );
		$this->_smarty->view = $this;
		
		//$this->assign_by_ref("this", $this );

    	//$this->cache_dir = APP_HOME.DIRECTORY_SEPARATOR.'temporary'.DIRECTORY_SEPARATOR.'cache';
		//$this->compile_dir = APP_HOME.DIRECTORY_SEPARATOR.'temporary'.DIRECTORY_SEPARATOR.'template_c';
		//$this->plugins_dir[] = APP_HOME.DIRECTORY_SEPARATOR.'lib'.DIRECTORY_SEPARATOR.'template'.DIRECTORY_SEPARATOR.'plugins';
    }
    
  	/**
     * Assign variables (other method)
     *
     *
    public function assign($spec, $value = null) {
        if (!is_array($spec)) {
            $spec = array($spec=>$value);
        }
        // Zend_Debug::dump( $spec );
        foreach ($spec as $key=>$val) {
            if ('_' == substr($key, 0, 1)) {
                require_once 'Zend/View/Exception.php';
                throw new Zend_View_Exception(
                    'Setting private var is not allowed',
                    $this);
            }
            $this->assign($key,$val);
        }
        return;
 
    }
    */
    /**
     * ?????????????????????
     *
     * @return Zend_View_Smarty
     */
    public function getEngine()
    {
        return $this->_smarty;
    }

    /**
     * ????????????????
     *
     * @param string $path ???????????????
     * @return void
     */
    public function setScriptPath($path)
    {
        if (is_readable($path)) {
            $this->_smarty->template_dir = $path;
      		return;
        }

        throw new Zend_Exception('invalid file path');
    }

    /**
     * ?????????????????????
     *
     * @return string
     */
    public function getScriptPaths()
    {
        return array($this->_smarty->template_dir);
    }

    /**
     * setScriptPath ???????
     *
     * @param string $path
     * @param string $prefix Unused
     * @return void
     */
    public function setBasePath($path, $prefix = 'Zend_View')
    {
        return $this->setScriptPath($path);
    }

    /**
     * setScriptPath ???????
     *
     * @param string $path
     * @param string $prefix Unused
     * @return void
     */
    public function addBasePath($path, $prefix = 'Zend_View')
    {
        return $this->setScriptPath($path);
    }

    /**
     * ???????????????
     *
     * @param string $key ???
     * @param mixed $val ????
     * @return void
     */
    public function __set($key, $val)
    {
        $this->assign($key, $val);
    }

    /**
     * empty() ? isset() ???????????????
     *
     * @param string $key
     * @return boolean
     */
    public function __isset($key)
    {
        return (null !== $this->_smarty->get_template_vars($key));
    }

    /**
     * ???????????????? unset() ???????????
     *
     * @param string $key
     * @return void
     */
    public function __unset($key)
    {
        $this->clear_assign($key);
    }

    /**
     * ???????????????
     *
     * ????????????????????????
     * ?? => ? ?????????????
     *
     * @see __set()
     * @param string|array $spec ???????? (??????? ?? => ? ???)
     * @param mixed $value (?????) ?????????????????????????
     * @return void
     *
     */
    
    public function assign($spec, $value = null) //$value = null)
    {
       	if (is_array($spec)) {
            $this->_smarty->assign($spec);
            return;
        }

        $this->_smarty->assign($spec, $value);
    }

    /**
     * ?????????????????
     *
     * Zend_View ? {@link assign()} ??????
     * ({@link __get()}/{@link __set()}) ?????????????????
     *
     * @return void
     */
    public function clearVars()
    {
        $this->_smarty->clear_all_assign();
    }

    /**
     * ???????????????????
     *
     * @param string $name ??????????
     * @return string ????
     */
    public function render($name)
    {
        return $this->_smarty->fetch($name);
    }

    public function display($name)
    {
    	//$filter = new Third_Filter_HeadHelperOutput();
		// $filter->setView( $this ); 

		// EXIBE O VIEW
		//echo $this->headLocaleOutput( $this->render($name) );
		echo $this->headLocaleOutput( $this->render($name) );
    }
        
/////////////////////TODO partial
     /**
     * Variable to which object will be assigned
     * @var string
     */
    protected $_objectKey;

    /**
     * Renders a template fragment within a variable scope distinct from the
     * calling View object.
     *
     * If no arguments are passed, returns the helper instance.
     *
     * If the $model is an array, it is passed to the view object's assign()
     * method.
     *
     * If the $model is an object, it first checks to see if the object
     * implements a 'toArray' method; if so, it passes the result of that
     * method to to the view object's assign() method. Otherwise, the result of
     * get_object_vars() is passed.
     *
     * @param  string $name Name of view script
     * @param  string|array $module If $model is empty, and $module is an array,
     *                              these are the variables to populate in the
     *                              view. Otherwise, the module in which the
     *                              partial resides
     * @param  array $model Variables to populate in the view
     * @return string|Zend_View_Helper_Partial
     */
    public function partial($name = null, $module = null, $model = null)
    {
        if (0 == func_num_args()) {
            return $this;
        }

        $view = $this->cloneView();
        if (isset($this->partialCounter)) {
            $view->partialCounter = $this->partialCounter;
        }
        if ((null !== $module) && is_string($module)) {
            require_once 'Zend/Controller/Front.php';
            $moduleDir = Zend_Controller_Front::getInstance()->getControllerDirectory($module);
            if (null === $moduleDir) {
                throw new Zend_View_Exception('Cannot render partial; module does not exist');
            }
            $viewsDir = dirname($moduleDir) . '/views';
            $view->addBasePath($viewsDir);
        } elseif ((null == $model) && (null !== $module)
            && (is_array($module) || is_object($module)))
        {
            $model = $module;
        }

        if (!empty($model)) {
        	
            if (is_array($model)) {
            	
                $view->assign($model);
            } elseif (is_object($model)) {
            	
                if (null !== ($objectKey = $this->getObjectKey())) {
                    $view->assign($objectKey, $model);
                } elseif (method_exists($model, 'toArray')) {
                    $view->assign($model->toArray());
                } else {
                    $view->assign(get_object_vars($model));
                }
            }
        }

        return $view->render($name);
    }

    /**
     * Clone the current View
     *
     * @return Zend_View_Interface
     */
    public function cloneView()
    {
        $view = clone $this;
      //  $view->clearVars();
        return $view;
    }

    /**
     * Set object key
     *
     * @param  string $key
     * @return Zend_View_Helper_Partial
     */
    public function setObjectKey($key)
    {
        if (null === $key) {
            $this->_objectKey = null;
        } else {
            $this->_objectKey = (string) $key;
        }

        return $this;
    }

    /**
     * Retrieve object key
     *
     * The objectKey is the variable to which an object in the iterator will be
     * assigned.
     *
     * @return null|string
     */
    public function getObjectKey()
    {
        return $this->_objectKey;
    }

//////////////// TODO

    /**
     * Render the provided pages.  This checks if $view->paginator is set and,
     * if so, uses that.  Also, if no scrolling style or partial are specified,
     * the defaults will be used (if set).
     *
     * @param  Zend_Paginator (Optional) $paginator
     * @param  string $scrollingStyle (Optional) Scrolling style
     * @param  string $partial (Optional) View partial
     * @param  array|string $params (Optional) params to pass to the partial
     * @return string
     * @throws Zend_View_Exception
     */
    public function paginationControl(Zend_Paginator $paginator = null, $scrollingStyle = null, $partial = null, $params = null)
    {
        if ($paginator === null) {
            if (isset($this->paginator) and $this->paginator !== null and $this->paginator instanceof Zend_Paginator) {
                $paginator = $this->paginator;
            } else {
                throw new Zend_View_Exception('No paginator instance provided or incorrect type');
            }
        }

        if ($partial === null) {
            if (self::$_defaultViewPartial === null) {
                throw new Zend_View_Exception('No view partial provided and no default set');
            }

            $partial = self::$_defaultViewPartial;
        }

        $pages = get_object_vars($paginator->getPages($scrollingStyle));

        if ($params !== null) {
            $pages = array_merge($pages, (array) $params);
        }

        if (is_array($partial)) {
            if (count($partial) != 2) {
                throw new Zend_View_Exception('A view partial supplied as an array must contain two values: the filename and its module');
            }

            if ($partial[1] !== null) {
                return $this->partial($partial[0], $partial[1], $pages);
            }

            $partial = $partial[0];
        }

        return $this->partial($partial, $pages);
    }

    /**
     * Sets the default view partial.
     *
     * @param string $partial View partial
     */
    public static function setDefaultViewPartial($partial)
    {
        self::$_defaultViewPartial = $partial;
    }

    /**
     * Gets the default view partial
     *
     * @return string
     */
    public static function getDefaultViewPartial()
    {
        return self::$_defaultViewPartial;
    }
    
    /**
     * Torna possivel a utilizacao de helper do Zend no Smarty
     * */
	public function setZendView(Zend_View_Interface $view)
	{
		$this->_zendView = $view;
		// $this->_helpers = $this->_zendView->_helpers;
	}

	public function callViewHelper($name,$args)
	{
		
		$helper = $this->_zendView->getHelper($name);

		return call_user_func_array(array($helper,$name),$args);
		
	}
	
	public function getPlaceHolder($name)
	{
		if(isset($this->_placeHolders[$name]))
			return $this->_placeHolders[$name];
		else
			return '';
	}

	public function createPlaceHolder($name,$content)
	{
		$this->_placeHolders[$name] = $content;
	}
    
    
}
